<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chat room websocket</title>
    <link rel="stylesheet" href="bootstrap.css">
    <script src="jquery-3.2.1.min.js"></script>
</head>
<body class="container" style="width: 60%">
<div class="form-group"></br>
    <a href="javascript:;" class="file">选择文件
        <input type="file" name="" onchange="fileOnchange()" id="fileId"> <span id="filename" style="color: red"></span>
    </a>
    <a href="javascript:;" onclick="uploadFileFun()" class="file">
        上传
    </a>
</div>
<div class="progress">
    <div id="speedP" class="progress-bar" role="progressbar" aria-valuenow="60"
         aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
    </div>
</div>

<div class="form-group"></br>
    <h5>传输信息</h5>
    <textarea id="message_content" class="form-control" readonly="readonly" cols="50"
              rows="10"></textarea>
</div>

<script>
    var socket;//websocket连接
    // var webSocketUrl = 'ws://127.0.0.1:8033/upload/';//websocketi连接地址
    var webSocketUrl = 'ws://172.17.200.130:8033/upload/';//websocketi连接地址
    var roomId = Number(Math.random().toString().substr(3, 3) + Date.now()).toString(36);//房间号，生成唯一的id
    var SpeedOfProgress = "";//进度
    var fileObject;//文件对象
    var uploadFlag = true;//文件上传的标识
    var paragraph = 10485760;//文件分块上传大小
    var startSize, endSize = 0;//文件的起始大小和文件的结束大小
    var i = 0;//第几部分文件
    createWebSocketConnect(roomId);//自动调用
    //创建websocket连接
    function createWebSocketConnect(roomId) {
        if (!socket) {//避免重复连接
            console.log(roomId);
            socket = new WebSocket(webSocketUrl + roomId);
            socket.onopen = function () {
                console.log("websocket已连接");
            };
            socket.onmessage = function (e) {
                if (uploadFlag) {
                    //服务端发送的消息
                    $("#message_content").append(e.data + '\n');
                }
            };
            socket.onclose = function () {
                console.log("websocket已断开");
            }
        }
    }

    //文件上传核心方法
    function uploadFileFun() {
        //文件对象赋值
        let filedata = fileObject;
        //切换保存标识的状态
        uploadFlag = false;
        //先向后台传输文件名
        let fileName = fileObject.name;
        //后台只接收字符串类型，我们定义一个字符串的json对象给后台解析
        let fileJson = {
            type: "fileName",
            data: fileName
        };

        //后台接收到文件名以后会正式开始传输文件
        socket.send(JSON.stringify(fileJson));

        //此处为文件上传的核心中的核心，涉及分块上传
        socket.onmessage = function (msg) {
            if (uploadFlag === false) {
                //开始上传文件
                if (msg.data === 'ok') {
                    //判断结束大小是否大于文件大小
                    if (endSize < filedata.size) {
                        $("#message_content").append("file.size:" + filedata.size+ '\n');
                        startSize = endSize;
                        endSize += paragraph;
                        $("#message_content").append("file.size:" + filedata.size+ '\n');
                        $("#message_content").append("startSize:" + startSize+'\n');
                        $("#message_content").append("endSize:" + endSize+'\n');
                        SpeedOfProgress = Math.round(startSize / filedata.size * 10000) / 100.00 + "%";
                        $("#speedP").css("width",SpeedOfProgress);
                        $("#message_content").append("Slice--->"+'\n');
                        var blob = filedata.slice(startSize, endSize);
                        var reader = new FileReader();
                        reader.readAsArrayBuffer(blob);
                        reader.onload = function loaded(evt) {
                            var ArrayBuffer = evt.target.result;
                            console.info("==ArrayBuffer=",ArrayBuffer);
                            $("#message_content").append("发送文件第" + (i++) + "部分"+'\n');
                            let fileObjJson={
                                type: "fileCount",
                                data:i
                            };
                            socket.send(JSON.stringify(fileObjJson));
                            socket.send(ArrayBuffer);
                        }
                    } else {
                        $("#speedP").css("width","100%");
                        $("#message_content").append("endSize >= file.size-->" + msg.data + "<---"+'\n');
                        $("#message_content").append("endSize >= file.size-->endSize:" + endSize+'\n');
                        $("#message_content").append("endSize >= file.size-->file.size:" + filedata.size+'\n');
                        startSize = endSize = 0;
                        i = 0;
                        $("#message_content").append("发送" + filedata.name + "完毕"+'\n');
                        $("#message_content").append("发送文件完毕"+'\n');
                        socketmess={
                            type:"over",
                            message:filedata.name
                        };
                        socket.send(JSON.stringify(socketmess));//告诉socket文件传输完毕，清空计数器
                    }
                } else {
                    //此处获取
                    $("#message_content").append("文件路径为："+msg.data+'\n');
                }
            }
        }


    }

    //监听file域对象的变化，然后用于回显文件名
    function fileOnchange() {
        //从file域对象获取文件对象
        let files = $("#fileId")[0].files;
        //存储文件对象
        fileObject = files[0];
        //回显文件名
        $("#filename").html(fileObject.name);
    }

</script>
<style>
    .file {
        position: relative;
        display: inline-block;
        background: #D0EEFF;
        border: 1px solid #99D3F5;
        border-radius: 4px;
        padding: 4px 12px;
        overflow: hidden;
        color: #1E88C7;
        text-decoration: none;
        text-indent: 0;
        line-height: 20px;
    }

    .file input {
        position: absolute;
        font-size: 100px;
        right: 0;
        top: 0;
        opacity: 0;
    }

    .file:hover {
        background: #AADFFD;
        border-color: #78C3F3;
        color: #004974;
        text-decoration: none;
    }
</style>
</body>
</html>
